//
//  BBPhotoAlbumTool.swift
//  BusinessBao
//
//  Created by Chen on 2017/7/20.
//  Copyright © 2017年 Chen. All rights reserved.
//

import UIKit
import AVFoundation

public enum selectPhotoType {
    case takePhoto//拍照
    case album//从相册选择
    
    init(_ type: Int) {
        if (type == 0) {
            self = .takePhoto
        } else {
            self = .album
        }
    }
}

class BBPhotoAlbumTool: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    let imagePicker = UIImagePickerController()
    var selectImageBlock: ((_ image: UIImage) -> ())?
    weak var vc: UIViewController?
    
    override init() {
        super.init()
    }
    
    /// 选择图片
    ///
    /// - Parameters:
    ///   - type: 选择图片类型
    ///   - currentVC: 当前所在控制器，用于present跳转触发器
    ///   - selectImageBlock: 图片选择后的回调
    func selectPhoto(type: selectPhotoType,
                     from currentVC: UIViewController,
                     selectImageBlock: @escaping ((_ image: UIImage) -> ())) {
        self.selectImageBlock = selectImageBlock
        self.vc = currentVC
        
        imagePicker.delegate = self as UIImagePickerControllerDelegate & UINavigationControllerDelegate
//        imagePicker.modalPresentationStyle = .fullScreen;
//        imagePicker.allowsEditing = true

        switch type {
        case .takePhoto:
            if (UIImagePickerController.isSourceTypeAvailable(.camera)) {
                if (self.checkCameraAuth()) {
                    imagePicker.sourceType = .camera
                    currentVC.present(imagePicker, animated: true, completion: nil)
                }
            } else {
                self.showAlert(with: "相机不可用")
            }
            break
        case .album:
            if (UIImagePickerController.isSourceTypeAvailable(.photoLibrary)) {
                imagePicker.sourceType = .photoLibrary
                currentVC.present(imagePicker, animated: true, completion: nil)
            }
            break
        }
    }
    
    func showAlert(with message:String) {
        BBAlertView.alertViewShow(In: self.vc!,
                                  title: message,
                                  message: "",
                                  buttonTitles: ["确定"],
                                  selectBlock: { (index) in
        })
    }
    
    func checkCameraAuth() -> Bool {
        var isAvalible = true
        let authStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)
        switch authStatus {
        case .notDetermined://用户尚未做出了选择这个应用程序的问候
            isAvalible = UIImagePickerController.isSourceTypeAvailable(.camera)
            break
        case .restricted://此应用程序没有被授权访问的照片数据。可能是家长控制权限。
            break
        case .denied://用户已经明确否认了这一照片数据的应用程序访问.
            isAvalible = false
            break
        case .authorized://用户已授权应用访问照片数据.
            break
        }
        if (isAvalible == false) {
            let appName = AppName!
            BBAlertView.alertViewShow(In: self.vc!,
                                      title: "相机权限",
                                      message: "您关闭了\(appName)的相机权限，可以在设置 > 隐私 > 相机中开启权限。",
                                      buttonTitles: [ "取消", "去设置"],
                                      selectBlock: { (index) in
                                        if index == 1 {
                                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
                                                UIApplication.shared.openURL(URL(string: UIApplicationOpenSettingsURLString)!)
                                            }
                                        }
            })
        }
        return isAvalible
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
            self.selectImageBlock?(image)
            picker.dismiss(animated: true, completion: nil)
        } else {
            picker.dismiss(animated: true, completion: nil)
            self.showAlert(with: "请选择正确的图片")
        }
    }
    
    
}
